<?php


namespace app\common\model;


use think\Db;

class Products extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_products';
    // 主键ID
    protected $pk = 'product_id';

    //审核商品类型
    public static $classlist = [
        '1'=>'普通商品',
        '2'=>'兑换商品',
        '3'=>'爱心餐品',
        '4'=>'团餐商品',
        '5'=>'点餐商品',
        '6'=>'展示菜品',
    ];

    /**
     * @param array $where  // 查询的条件
     * @param string $item  // 查询的参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getOne($where=[1], $item='*')
    {
        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

    function get_list($cond, $orderby, $item)
    {

        $where = null;

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }

        if(is_numeric($cond['utype'])){
            $where[] = ['utype', '=', $cond['utype']];
        }
        if(!empty($cond['type'])){
            $where[] = ['type', '=', $cond['type']];
        }
        if(!empty($cond['spf_id'])){
            $where[] = ['spf_id', '=', $cond['spf_id']];
        }

        if(!empty($cond['shopid'])){
            $where[] = ['shopid', '=', $cond['shopid']];
        }

        if(!empty($cond['state'])){
            $where[] = ['state', '=', $cond['state']];
        }

        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->select();
        return $rs;
    }

    function admin_get_list($cond, $orderby = 'p.product_id desc', $item = '*',$limit,$join =
    [
        ['ddt_shops s','s.shop_id = p.shop_id'],
        ['ddt_products_type pt','pt.type_id = p.type_id'],
    ])
    {

        $where = null;

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }

        if(!empty($cond['type'])){
            $where[] = ['type', '=', $cond['type']];
        }

        if(!empty($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }

        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }

        if(!empty($cond['shop_name'])){
            $where[] = ['s.shop_name','like',"%".$cond['shop_name']."%"];
        }
        if(!empty($cond['product_name'])){
            $where[] = ['p.product_name','like',"%".$cond['product_name']."%"];
        }
        if(!empty($cond['type_id'])){
            $where[] = ['pt.type_id','=',$cond['type_id']];
        }

        $rs = $this
            ->alias('p')
            ->leftJoin($join)
            ->where($where)
            ->field($item)
            ->order($orderby)
            ->paginate($limit);
        return $rs;
    }

    // 获取分页列表
    function get_list_page($cond,$orderby,$item,$limit)
    {
        $where = null;
//        if(!empty($cond['group_name'])){
//            $where[] = ['group_name','like',"%".$cond['group_name']."%"];
//        }

        // 审核状态
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }

        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }

        $rs = Db::table($this->table)
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->leftJoin('ddt_products_type t','p.type_id = t.type_id')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);

        return $rs;
    }

    //新增、编辑(后台操作)
    function editstatus($params, $id=0){
        $product = $this->getOne(array('id'=>$id));
        if($product['utype'] == '4' && $product['is_produce'] == '1'){
            if($product['approved'] != '1'){$this->setError(-1,'商品审核未通过');return false;}
        }
        // 更新条件
        $where = ['id' => $id];
        $rs = $this->allowField(true)->save($params, $where);
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ['product_id' => $id];
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            $params['createat'] = time();
            // 更新数据
            $this->allowField(true)->save($params);
            $rs = $this->{$this->pk};
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        $id > 0? $rs = $id:'';
        return $rs;
    }

	function GetProductsList($cond,$orderby){
		$field = "id,type,utype,shopid,name,sidedish,remark,price,weight,isdiscount,sprice,salecount,menuimage,manufacturedate,qualityperiod,stocknum,issprice";
		$where = null;

		if(!empty($cond['utype']) && is_numeric($cond['utype'])){
			$where[] = ['utype', '=', $cond['utype']];
			$where2[] = ['utype', '=', $cond['utype']];
		}
		if(!empty($cond['type']) && is_numeric($cond['type'])){
			$where[] = ['type', '=', $cond['type']];
			$where2[] = ['type', '=', $cond['type']];
		}
		if($cond['isstock'] == true){
			$where[] = ['stocknum','>','0'];
//            $where2[] = ['stocknum','<=','0'];
			$orwhere[] = ['stocknum','<=','0'];
		}

		if(!empty($cond['shopid'])){
			$where[] = ['shopid', '=', $cond['shopid']];
			$where2[] = ['shopid', '=', $cond['shopid']];
		}

		if(!empty($cond['state']) && is_numeric($cond['state'])){
			$where[] = ['state', '=', $cond['state']];
			$where2[] = ['state', '=', $cond['state']];
		}
		$orwhere[] = ['qualityperiod','<',date('Y-m-d',time())];
		$update = [
			'state' => $cond['state'],
		];
		$this->edit2($update,$where2,$orwhere);
		$rs = Db::table($this->table)
			->field($field)
			->where($where)
			->order($orderby)
			->select();
		return $rs;
	}

	function ProductsChecked($cond){
		$field = "id,type,utype,shopid,name,sidedish,remark,price,weight,isdiscount,sprice,salecount,menuimage,manufacturedate,qualityperiod";
		$where = null;

		if(is_numeric($cond['utype'])){
			$where[] = ['utype', '=', $cond['utype']];
		}
		if(!empty($cond['isstock'] && $cond['isstock'] == true)){
			$where[] = ['stocknum','>','0'];
		}

		if(!empty($cond['shopid'])){
			$where[] = ['shopid', '=', $cond['shopid']];
		}

		if(!empty($cond['prodids'] && is_array($cond['prodids']))){
			$ids = [];
			foreach($cond['prodids'] as $key => $value){
				$ids[$key] = $value['good_id'];
			}
			$where[] = ['id', 'in' , $ids];
		}

		if(!empty($cond['state'])){
			$where[] = ['state', '=', $cond['state']];
		}
		$rs = Db::table($this->table)
			->field($field)
			->where($where)
			->select();
		return $rs;
	}

    // 商品增加销量
    function addsalecount($where){
        $rs = $this
            ->where($where)
            ->setInc('salecount');
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

	// 批量审核通过
    function ProductsAdopt($ids)
    {
        // 原生更新
        $rs = $this->execute("UPDATE ddt_products SET approved = 2 WHERE product_id in (".$ids.")");
        return $rs;
    }


////    h5获取商品列表
//    function get_product_list($cond, $orderby, $item = 'p.*',$limit,$is_get_stock = false,$is_get_show = false)
//    {
//        $where = null;
//        if(!empty($cond['product_name'])){
//            $where[] = ['p.product_name', 'like', '%'.$cond['product_name'].'%'];
//        }
//        if(!empty($cond['type_id'])){
//            $where[] = ['p.type_id', '=', $cond['type_id']];
//        }
//        if(isset($cond['shop_id'])){
//            $where[] = ['p.shop_id', '=', $cond['shop_id']];
//        }
//        if(!empty($cond['approved'])){
//            $where[] = ['p.approved', '=', $cond['approved']];
//        }
//        if(!empty($cond['state'])){
//            $where[] = ['p.state', '=', $cond['state']];
//        }
//        if(!empty($cond['is_del'])){
//            $where[] = ['p.is_del', '=', $cond['is_del']];
//        }
//        if(!empty($cond['shop_approved'])){
//            $where[] = ['s.approved', '=', $cond['shop_approved']];
//        }
//        if(!empty($cond['shop_state'])){
//            $where[] = ['s.state', '=', $cond['shop_state']];
//        }
//        if(!empty($cond['class_id'])){
//            $where[] = ['p.class_id', '=', $cond['class_id']];
//        }
//        if(!empty($cond['lon']) && !empty($cond['lat'])){
//            $item .= ",FLOOR((st_distance (point (s.lon, s.lat), point({$cond['lon']}, {$cond['lat']}) ) * 111195)+1) AS distance";
//            $orderby['distance'] = "ASC";
//        }
//
//        $rs = $this
//            ->alias('p')
//            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
//            ->field($item)
//            ->where($where)
//            ->where('(select count(p_s_id) from ddt_products_stock ps where ps.product_id = p.product_id and is_del = 1) > 0')
//            ->order($orderby);
//        if($is_get_stock){
//            $with = [
//                'stocks' => function($query) {
//                    $query->where('is_del','=',1)
//                        ->field('product_id,p_s_id,p_s_name,stock');
//                }
//            ];
//            $rs = $rs->with($with);
//        }
//        $rs = $rs->paginate($limit);
//        if($is_get_show){
//            $typeModel = new ProductsType();
//            $rs = $rs->each(function($item) use($typeModel){
//               $typers = $typeModel->checkshowtype($item['type_id']);
////               var_dump($typers);
//               $typers['can_show'] == 2?$item['can_show'] = true:$item['can_show'] = false;
//               return $item;
//            });
//        }
//        return $rs;
//    }

//    h5获取商品列表
    function get_product_list($cond, $orderby, $item = 'p.*')
    {
        $where = null;
        if(!empty($cond['product_name'])){
            $where[] = ['p.product_name', 'like', '%'.$cond['product_name'].'%'];
        }
        if(!empty($cond['type_id'])){
            $where[] = ['p.type_id', '=', $cond['type_id']];
        }
        if(isset($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }
        if(!empty($cond['shop_approved'])){
            $where[] = ['s.approved', '=', $cond['shop_approved']];
        }
        if(!empty($cond['shop_state'])){
            $where[] = ['s.state', '=', $cond['shop_state']];
        }
        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }
        if(!empty($cond['lon']) && !empty($cond['lat'])){
            $item .= ",FLOOR((st_distance (point (s.lon, s.lat), point({$cond['lon']}, {$cond['lat']}) ) * 111195)+1) AS distance";
            $orderby['distance'] = "ASC";
        }

        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->select();
        return $rs;
    }

    /**
     * 建立和ProductStock的关联
     * hasMany方法的参数包括:hasMany('关联模型名','外键名','主键名',['模型别名定义']);
     */
    public function stocks(){
        return $this->hasMany('ProductStock','product_id');
    }

//    h5获取非普通商品列表
    function get_uncommon_list($cond, $orderby, $item = 'p.*',$limit)
    {
        $where = null;
        if(!empty($cond['product_name'])){
            $where[] = ['p.product_name', 'like', '%'.$cond['product_name'].'%'];
        }
        if(!empty($cond['type_id'])){
            $where[] = ['p.type_id', '=', $cond['type_id']];
        }
        if(isset($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['shop_approved'])){
            $where[] = ['s.approved', '=', $cond['shop_approved']];
        }
        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['shop_state'])){
            $where[] = ['s.state', '=', $cond['shop_state']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }
        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }
        if(!empty($cond['stock_del'])){
            $where[] = ['ps.is_del', '=', $cond['stock_del']];
        }
//        var_dump($where);die;
        if(!empty($cond['lon']) && !empty($cond['lat'])){
            $item .= ",FLOOR((st_distance (point (s.lon, s.lat), point({$cond['lon']}, {$cond['lat']}) ) * 111195)+1) AS distance";
            $orderby['distance'] = "ASC";
        }
//        print_r($orderby);die;
        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_products_stock ps','ps.product_id = p.product_id')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->where($where)
            ->order($orderby)
            ->field($item)
            ->paginate($limit);
//            ->each(function($value){
//                if(!$value['shop_id']){
////                    $value['shop_id'] = 0;
//                    $value['shop_name'] = '总部';
//                }
//                return $value;
//            });
//        print_r($rs);die;
        return $rs;
    }

//    h5获取每周热门商品列表
//    function get_hot_list($cond, $orderby, $item = 'p.*',$limit,$is_hot = false)
    function get_hot_list($cond, $item = 'p.*',$limit)
    {
        $where = null;
        if(!empty($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }
        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }
        if(!empty($cond['shop_approved'])){
            $where[] = ['s.approved', '=', $cond['shop_approved']];
        }
        if(!empty($cond['shop_state'])){
            $where[] = ['s.state', '=', $cond['shop_state']];
        }
        if(!empty($cond['lon']) && !empty($cond['lat'])){
            $item .= ",FLOOR((st_distance (point (s.lon, s.lat), point({$cond['lon']}, {$cond['lat']}) ) * 111195)+1) AS distance";
            $orderby['distance'] = "ASC";
        }

//        if($is_hot){
            $sdefaultDate = date("Y-m-d");
            //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
            $first=1;
            //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
            $w=date('w',strtotime($sdefaultDate));
            //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
//            $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
            $week_start=strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days');
            //本周结束日期
            $week_end=strtotime(date('Y-m-d',$week_start)." +7 days");
//            var_dump($w);
//            var_dump($week_end);die;
//            var_dump($week_start);die;
            $item .= ",(select sum(quantity) as sales from ddt_orderdetail od join ddt_order o on od.order_id = o.order_id where o.order_status = 4 and od.product_id = p.product_id and o.order_time between ".$week_start." and ".$week_end.") as totalsales";
            $orderby["totalsales"] = "desc";
//        }

        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);
//        echo $this->getLastSql();die;
        return $rs;
    }

//    h5获取展示菜品列表
    function get_show_list($cond, $item = 'p.*',$orderby = 'p.sort desc',$limit)
    {
        $where = null;
        if(!empty($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }
        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }
        if(!empty($cond['shop_approved'])){
            $where[] = ['s.approved', '=', $cond['shop_approved']];
        }
        if(!empty($cond['shop_state'])){
            $where[] = ['s.state', '=', $cond['shop_state']];
        }

        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);
//        echo $this->getLastSql();die;
        return $rs;
    }

//    h5获取普通商品详情
    function get_product_detail($data,$item = '*')
    {
        $where = [
            ['product_id', '=', $data['product_id']],
            ['approved', '=', 2],
            ['state', '=', 1],
            ['is_del', '=', 1],
            ['class_id','=',$data['class_id']],
        ];

        $rs = $this
            ->alias('p')
            ->field($item)
            ->where($where)
            ->find();
        $data = null;
        if(!empty($rs)){
            $data = $rs->toArray();
            $shopModel = new Shops();
            $shop = $shopModel->getOneShop($data['shop_id'],'*');
            $data['shop'] = empty($shop)?null:$shop->toArray();
            $stockModel = new ProductStock();
            $stocks = $stockModel
                ->where([
                    'product_id' => $data['product_id'],
                    'is_del' => 1
                ])
                ->select();
            $data['stocks'] = $stocks->toArray();
            $imageModel = new ProductImage();
            $images = $imageModel
                ->where([
                    'product_id' => $data['product_id'],
                    'is_show' => 1
                ])
                ->order("sort asc")
                ->select();
//            var_dump($images->toArray());die;
            $data['images'] = $images->toArray();
        }
        return $data;
    }

//    验证商品是否已收藏
    function product_is_collect($user,$product_id,$stock_id = 0){
        $collectModel = new Collection();
        $where = [
            ['user_id','=',$user['user_id']],
            ['product_id','=',$product_id],
        ];
        if(!empty($stock_id)){
            $where[] = ['p_s_id','=',$stock_id];
        }
        $collection = $collectModel->getOne($where,'*');
        if(empty($collection)){
            return false;
        }
        return true;
    }

//    h5获取非普通商品详情
    function get_uncommon_product_detail($data,$item = 'p.*')
    {
        $where = [
            ['p.approved', '=', 2],
            ['p.state', '=', 1],
            ['p.is_del', '=', 1],
        ];
        if(!empty($data['product_id'])){
            $where[] = ['p.product_id', '=', $data['product_id']];
        }
        if(!empty($data['class_id'])){
            $where[] = ['p.class_id','=',$data['class_id']];
        }
        if(!empty($data['class_ids'])){
            is_array($data['class_ids'])?$ids = implode(',',$data['class_ids']):$ids = $data['class_ids'];
            $where[] = ['p.class_id','=',$ids];
        }
        if(!empty($data['stock_id'])){
            $where[] = ['ps.p_s_id','=',$data['stock_id']];
        }
        if(!empty($data['stock_del'])){
            $where[] = ['ps.is_del','=',$data['stock_del']];
        }

        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_products_stock ps','ps.product_id = p.product_id')
            ->where($where)
            ->field($item)
            ->find();
        $data = null;
        if(!empty($rs)){
            $data = $rs->toArray();
            $shopModel = new Shops();
            $shop = $shopModel->getOneShop($data['shop_id'],'*');
            $data['shop'] = empty($shop)?null:$shop->toArray();
            $data['images'] = [];
        }
        return $data;
    }

//    校验非普通商品
    function check_uncommon_product($product_id,$stock_id,$item = 'p.*')
    {
        $where = [
            ['p.product_id','=',$product_id],
            ['p.approved', '=', 2],
            ['p.state', '=', 1],
            ['p.is_del', '=', 1],
            ['p.class_id','<>',1],
            ['ps.is_del','=',1],
            ['ps.p_s_id','=',$stock_id],
            ['s.approved','=',1],
            ['s.state','=',1],
        ];

        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_products_stock ps','ps.product_id = p.product_id')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->where($where)
            ->field($item)
            ->find();
        if(!$rs){
            $this->setError(-1,"商品或者店铺已下架");
            return false;
        }
        return $rs->toArray();
    }
}